package webshop.controller.action;

import webshop.model.bl.CustomerManager;
import webshop.model.db.Customer;

import com.opensymphony.xwork2.ActionSupport;

public class RegistrationAction extends ActionSupport {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 8235698705561928620L;
	
	private String username;
	private String password;
	private String firstname;
	private String lastname;
	private String email = "";
	private String resident = "";
	private Integer zipCode;
	private String street = "";
	
	@Override
	public String execute() throws Exception {
		Customer customer = new Customer(username, password, lastname, firstname, email, resident, zipCode, street, false);
		try {
			new CustomerManager().saveCustomer(customer);
		} catch (Throwable ex) {
			addActionError("benutzer konnte nicht registriert werden!");
			return "input";
		}
		
		return "successUser";
	}
	
	@Override
	public void validate() {
		boolean emptyFields = false;
		if ("".equals(username)) {
			addFieldError("username", "");
			emptyFields = true;
		} else if (new CustomerManager().usernameExists(username)) {
			addFieldError("username", "");
			addActionError(getText("error.username.exists.already"));
		}
		if ("".equals(password)) {
			emptyFields = true;
			addFieldError("password", "");
		}
		if ("".equals(firstname)) {
			emptyFields = true;
			addFieldError("firstname", "");
		}
		if ("".equals(lastname)) {
			emptyFields = true;
			addFieldError("lastname", "");
		}
		if (emptyFields) {
			addActionError(getText("error.empty.fields"));
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getFirstname() {
		return firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getResident() {
		return resident;
	}

	public void setResident(String resident) {
		this.resident = resident;
	}

	public Integer getZipCode() {
		return zipCode;
	}

	public void setZipCode(int zipCode) {
		this.zipCode = zipCode;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public void setPassword(String password) {
		this.password = password;
	}
		
}
